package com.nf.dao;

import com.nf.entity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test1 {

    public static void main(String[] args){
       /* //mybatis的配置文件
        String resource="mybatis-config.xml";
        //使用加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is=Test1.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession的工厂
        //sqlSessionFactor工厂 是拿来装SqlSession的
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //使用MyBatis提供的Resources类加载mybatis的配置文件（它也加载关联的映射文件）
        //Reader reader = Resources.getResourceAsReader(resource);
        //构建sqlSession的工厂
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //创建能执行映射文件中sql的sqlSession
        SqlSession session=sessionFactory.openSession();
        *//**
         * 映射sql的标识字符串，
         * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值，
         * getUser是select标签的id属性值，通过select标签的id属性值就可以找到要执行的SQL
         * *//*

        //String statement="mapper.StudentMapper.findStudentById";
        String statement="mapper.StudentMapper.findAllStudents";
        //执行查询返回一个唯一Student对象的sql
        //Student student=session.selectOne(statement,1);
        Student student=session.selectOne(statement);
        System.out.println(student);*/

        //用流加载mybatis-config.xml文件，它从根部开始
        InputStream inputStream = null;
        try {
            //用流加载mybatis-config.xml文件，它从根部开始
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            System.out.println("加载配置文件config.xml时报错："+e.getMessage());
        }
        //new一个SqlSession工厂生成器
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //SqlSession工厂建造  就是开始建造工厂
        SqlSessionFactory factory = builder.build(inputStream);
        //SqlSession 开始生产
        SqlSession sqlSession = factory.openSession();
        //StudentMapper接口
        StudentMapper stuDao=null;
        //映射StudentMapper类， 生产的地方
        stuDao = sqlSession.getMapper(StudentMapper.class);
        //输出
        List<Student> studentList=stuDao.findAllStudents();
        for(Student s:studentList){
            System.out.println(s.getName());
        }
    }
}
